package com.oswift.cms.web.backstage;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.cms.entity.AdminBean;
import com.oswift.cms.entity.ChannelBean;
import com.oswift.cms.entity.CommonModelBean;
import com.oswift.cms.entity.DictionaryBean;
import com.oswift.cms.entity.ErrorBean;
import com.oswift.cms.entity.MessageBean;
import com.oswift.cms.entity.PageBean;
import com.oswift.cms.entity.PicBean;
import com.oswift.cms.entity.PicUrlBean;
import com.oswift.cms.entity.UploadBean;
import com.oswift.cms.service.IChannelService;
import com.oswift.cms.service.IPicService;
import com.oswift.cms.system.cache.CMSCacheFileds;
import com.oswift.cms.system.cache.DictionaryManager;
import com.oswift.cms.utils.Field;
import com.oswift.cms.utils.PageCode;
import com.oswift.cms.utils.Field.PageName;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.StringUtil;
import com.oswift.utils.exception.PlatException;

@Controller
@RequestMapping("/security")
public class PicAction extends BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(PicAction.class);

    /**
     * PicServiceImpl注入对象
     */
    @Resource
    private IPicService picService;

    /**
     * ChannelServiceImpl注入对象
     */
    @Resource
    private IChannelService channelService;

    /**
     *
     * 获取公共内容信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/getPicList", method = RequestMethod.GET)
    public ModelAndView getPicList(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String orderField = request.getParameter("orderField");
            String orderType = request.getParameter("orderType");
            String s_Status = request.getParameter("status");
            String s_ChannelId = request.getParameter("channelId");
            String searchType = request.getParameter("searchType");
            String keyword = request.getParameter("keyword");
            String s_PageNum = request.getParameter("pageNum");

            int status = Field.Status.ALL;
            if (!StringUtil.isEmpty(s_Status))
            {
                status = Integer.valueOf(s_Status);
            }
            int channelId = -1;
            if (!StringUtil.isEmpty(s_ChannelId))
            {
                channelId = Integer.valueOf(s_ChannelId);
            }
            int pageNum = DEFAULT_PAGENUM;
            if (!StringUtil.isEmpty(s_PageNum))
            {
                pageNum = Integer.valueOf(s_PageNum);
            }

            // 权限判断
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            PageBean<CommonModelBean> bean = picService.getCommonModel(orderField, orderType,
                    status, channelId, searchType, keyword, this.pageRecordNum,
                    pageNum, Field.TableName.PICURL, companyId);

            // 获取包含文章板块的栏目
            DictionaryBean dictionaryBean = DictionaryManager
                    .getValue(CMSCacheFileds.BusinessField.DEFAULT_PICURL_KEY);
            List<ChannelBean> channelList = channelService.getChannelList2(
                    companyId, dictionaryBean.getFieldValue());

            mv = new ModelAndView(PageName.PIC_LIST);
            mv.addObject("pageBean", bean);
            mv.addObject("status", status);
            mv.addObject("channels", channelList);
            mv.addObject("orderType", orderField + "_" +orderType);
            mv.addObject("channelId", channelId);
        }
        catch (PlatException e)
        {
            log.error("Get PicList info is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(e.getMessage());
            mv.addObject("bean", bean);
        }

        return mv;
    }

    /**
     *
     * 加载图片新增页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadAddPic", method = RequestMethod.GET)
    public ModelAndView loadAddPic(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            mv = picService.loadAddPic(PageName.PIC, companyId);
            mv.addObject(METHOD, METHOD_ADD);
        }
        catch (PlatException e)
        {
            log.error("The method of loadAddPic is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadAddPic is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 加载图片修改页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUpdatePic", method = RequestMethod.GET)
    public ModelAndView loadUpdatePic(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
                return mv;
            }
            AdminBean adminBean = this.getAdmin(request);
            int companyId = adminBean.getCompanyID();

            mv = picService.loadUpdatePic(PageName.PIC, companyId, Integer
                    .valueOf(id));
            mv.addObject(METHOD, METHOD_UPDATE);
        }
        catch (PlatException e)
        {
            log.error("The method of loadUpdatePic is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of loadUpdatePic is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 添加图片信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/addPic", method = RequestMethod.POST)
    @ResponseBody
    public Object addPic(HttpServletRequest request, PicBean bean)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            if (StringUtil.isEmpty(bean.getTitle()) || bean.getChannelId() <= 0)
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            if (StringUtil.isEmpty(bean.getPicUrls()))
            {
                messBean.setCode(PageCode.PICURL_ISEMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.PICURL_ISEMPTY));
                return messBean;
            }

            ObjectMapper mapper = new ObjectMapper();
            PicUrlBean[] beans = mapper.readValue(bean.getPicUrls(),
                    PicUrlBean[].class);
            List<PicUrlBean> list = Arrays.asList(beans);
            bean.setList(list);

            AdminBean adminBean = getAdmin(request);
            bean.setCompanyId(adminBean.getCompanyID());
            bean.setTableName(Field.TableName.PICURL);
            bean.setInputer(adminBean.getAdminName());
            if(StringUtil.isEmpty(bean.getDefaultPicUrl()))
            {
                bean.setDefaultPicUrl(null);
            }

            boolean isSuccess = picService.save(bean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.PIC_ADD_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.PIC_ADD_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.PIC_ADD_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of addPic is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of addPic is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 添加图片信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/updatePic", method = RequestMethod.POST)
    @ResponseBody
    public Object updatePic(PicBean bean)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            if (bean.getCommonModelId() <= 0)
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            if (StringUtil.isEmpty(bean.getTitle()) || bean.getChannelId() <= 0)
            {
                messBean.setCode(PageCode.TEXTFIELD_ISNOT_EMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.TEXTFIELD_ISNOT_EMPTY));
                return messBean;
            }

            if (StringUtil.isEmpty(bean.getPicUrls()))
            {
                messBean.setCode(PageCode.PICURL_ISEMPTY);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.PICURL_ISEMPTY));
                return messBean;
            }

            ObjectMapper mapper = new ObjectMapper();
            PicUrlBean[] beans = mapper.readValue(bean.getPicUrls(),
                    PicUrlBean[].class);
            List<PicUrlBean> list = Arrays.asList(beans);
            bean.setList(list);

            boolean isSuccess = picService.update(bean);
            if (isSuccess)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.PIC_UPDATE_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.PIC_UPDATE_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.PIC_UPDATE_FAIL));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of updatePic is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of updatePic is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    /**
     *
     * 加载图片频道上传页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUploadPic", method = RequestMethod.GET)
    public ModelAndView loadUploadPic(HttpServletRequest request)
    {
        String iframe = request.getParameter("iframe");
        ModelAndView mv = new ModelAndView(PageName.UPLOADPIC);
        mv.addObject("iframe", iframe);
        return mv;
    }

    /**
     *
     * 加载图片频道外部图片页面
     *
     * @author zhuou
     */
    @RequestMapping(value = "/loadUploadExPic", method = RequestMethod.GET)
    public ModelAndView loadUploadExPic(HttpServletRequest request)
    {
        String iframe = request.getParameter("iframe");
        ModelAndView mv = new ModelAndView(PageName.UPLOADEXTERNALPIC);
        mv.addObject("iframe", iframe);
        return mv;
    }

    /**
     *
     * 图片频道上传功能
     *
     * @author zhuou
     */
    @RequestMapping(value = "/uploadPic", method = RequestMethod.POST)
    public ModelAndView uploadPic(HttpServletRequest request)
    {
        ModelAndView mv = new ModelAndView(PageName.UPLOADPICRESULT);

        String picName = decodeKeyword(request.getParameter("txt_picName"));
        String picAuthor = decodeKeyword(request.getParameter("txt_picAuthor"));
        String picIntro = decodeKeyword(request.getParameter("txt_picIntro"));
        String iframe = request.getParameter("iframe");

        MessageBean messBean = new MessageBean();
        try
        {
            UploadBean uploadBean = picService.uploadImg(request, this
                    .getAdmin(request).getCompanyID());

            if (PageCode.COMMON_SUCCESS.equals(uploadBean.getState()))
            {
                // 将bean回传到页面
                PicUrlBean bean = new PicUrlBean();

                bean.setPicName(picName);
                bean.setPicIntro(picIntro);
                bean.setPicAuthor(picAuthor);
                bean.setPicUrl(uploadBean.getRelativePath());

                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(bean);
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(json);
            }

            mv.addObject("bean", messBean);
            mv.addObject("iframe", iframe);
        }
        catch (Exception e)
        {
            messBean.setCode(PageCode.UPLOAD_IMG_FAIL);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.UPLOAD_IMG_FAIL)
                    + e.getMessage());
            mv.addObject("bean", messBean);
        }

        return mv;
    }

    /**
     *
     * 获取图片的外部链接
     *
     * @author zhuou
     */
    @RequestMapping(value = "/uploadExPic", method = RequestMethod.POST)
    public ModelAndView uploadExPic(HttpServletRequest request)
    {
        ModelAndView mv = new ModelAndView(PageName.UPLOADPICRESULT);
        MessageBean messBean = null;
        try
        {
            String picName = decodeKeyword(request.getParameter("txt_picName"));
            String picAuthor = decodeKeyword(request
                    .getParameter("txt_picAuthor"));
            String picIntro = decodeKeyword(request
                    .getParameter("txt_picIntro"));
            String isDownload = decodeKeyword(request
                    .getParameter("txt_isDownload"));
            String picUrl = decodeKeyword(request.getParameter("txt_picUrl"));
            String iframe = request.getParameter("iframe");

            // 将bean回传到页面
            PicUrlBean bean = new PicUrlBean();
            bean.setPicName(picName);
            bean.setPicIntro(picIntro);
            bean.setPicAuthor(picAuthor);
            bean.setPicUrl(picUrl);

            // 是否下载
            if (Field.TRUE.equals(isDownload))
            {
                messBean = picService.download(request, picUrl, this.getAdmin(
                        request).getCompanyID(), picName);
                if (PageCode.COMMON_SUCCESS.equals(messBean.getCode()))
                {
                    bean.setPicUrl(messBean.getContent());
                }
            }
            else
            {
                messBean = new MessageBean();
                messBean.setCode(PageCode.COMMON_SUCCESS);
            }

            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(bean);
            messBean.setContent(json);
            mv.addObject("bean", messBean);
            mv.addObject("iframe", iframe);
        }
        catch (PlatException e)
        {
            messBean = new MessageBean();
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode())
                    + e.getMessage());
            mv.addObject("bean", messBean);
        }
        catch (Exception e)
        {
            messBean = new MessageBean();
            messBean.setCode(PageCode.UPLOAD_IMG_FAIL);
            messBean.setContent(ResourceManager
                    .getValue(PageCode.UPLOAD_IMG_FAIL)
                    + e.getMessage());
            mv.addObject("bean", messBean);
        }

        return mv;
    }

    /**
     *
     * 图片详情
     *
     * @author zhuou
     */
    @RequestMapping(value = "/picDetail", method = RequestMethod.GET)
    public ModelAndView picDetail(HttpServletRequest request)
    {
        ModelAndView mv = null;
        try
        {
            String id = request.getParameter("id");
            if (StringUtil.isEmpty(id))
            {
                mv = new ModelAndView(PageName.ERROR_PAGE);
                ErrorBean bean = new ErrorBean();
                bean.setCode(PageCode.GET_WEBPARAM_FAIL);
                bean.setMessInfo(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                mv.addObject("bean", bean);
                return mv;
            }

            PicBean bean = picService.getOne(Integer.valueOf(id));
            mv = new ModelAndView(PageName.PICDETAIL);
            mv.addObject("picBean", bean);
        }
        catch (PlatException e)
        {
            log.error("The method of picDetail is error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(e.getExceptionCode());
            bean.setMessInfo(ResourceManager.getValue(e.getExceptionCode()));
            mv.addObject("bean", bean);
        }
        catch (Exception e)
        {
            log.error("The method of picDetail is system's error.", e);
            mv = new ModelAndView(PageName.ERROR_PAGE);
            ErrorBean bean = new ErrorBean();
            bean.setCode(PageCode.SYSTEM_ERROR);
            bean.setMessInfo(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
            mv.addObject("bean", bean);
        }
        return mv;
    }

    /**
     *
     * 删除图片信息
     *
     * @author zhuou
     */
    @RequestMapping(value = "/delPic", method = RequestMethod.POST)
    @ResponseBody
    public Object delPic(HttpServletRequest request)
    {
        MessageBean messBean = new MessageBean();
        try
        {
            String id = request.getParameter("ids");
            if (StringUtil.isEmpty(id))
            {
                messBean.setCode(PageCode.GET_WEBPARAM_FAIL);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.GET_WEBPARAM_FAIL));
                return messBean;
            }

            int delSuccessNum = 0;
            int delFailNum = 0;
            String[] array = id.split(Field.COMMA);
            for (String i : array)
            {
                boolean isSuccess = picService.delete(Integer.valueOf(i));
                if (isSuccess)
                {
                    delSuccessNum++;
                }
                else
                {
                    delFailNum++;
                }
            }

            if (delSuccessNum == array.length)
            {
                messBean.setCode(PageCode.COMMON_SUCCESS);
                messBean.setContent(ResourceManager
                        .getValue(PageCode.PIC_DEL_SUCCESS));
            }
            else
            {
                messBean.setCode(PageCode.PIC_DEL_FAIL);
                String mess = ResourceManager.getValue(PageCode.PIC_DEL_FAIL);
                messBean.setContent(StringUtil.replace(mess, String
                        .valueOf(delSuccessNum), String.valueOf(delFailNum)));
            }
        }
        catch (PlatException e)
        {
            log.error("The method of delPic is error.", e);
            messBean.setCode(e.getExceptionCode());
            messBean.setContent(ResourceManager.getValue(e.getExceptionCode()));
        }
        catch (Exception e)
        {
            log.error("The method of delPic is system's error.", e);
            messBean.setCode(PageCode.SYSTEM_ERROR);
            messBean.setContent(ResourceManager.getValue(PageCode.SYSTEM_ERROR)
                    + e.getMessage());
        }
        return messBean;
    }

    public void setPicService(IPicService picService)
    {
        this.picService = picService;
    }

    public void setChannelService(IChannelService channelService)
    {
        this.channelService = channelService;
    }
}